//
//  NSData+IMB.m
//  ArtPraise
//
//  Created by 闫建刚 on 14-6-1.
//  Copyright (c) 2014年 闫建刚. All rights reserved.
//

#import "NSData+IMB.h"
#import "GTMBase64.h"

@implementation NSData (IMB)

/**  --# 字符串转换 ↓ #--  **/

// 转换为UTF8字符串
- (NSString*) stringForUTF8{
    return [self stringForEncoding:NSUTF8StringEncoding];
}

// 按照指定字符集转换字符串
- (NSString*) stringForEncoding:(NSStringEncoding)encoding{
    return [[NSString alloc]initWithData:self encoding:encoding];
}

/**  --# 字符串转换 ↑ #--  **/

/**  --# base64编码处理 ↓ #--  **/

// 按照UTF8字符集执行base64编码
- (NSString*)base64EncodingForUTF8{
    return [self base64EncodingForEncoding:NSUTF8StringEncoding];
}

// 按照指定字符集执行base64编码
- (NSString*)base64EncodingForEncoding:(NSStringEncoding)encoding;
{
    NSData *data = [GTMBase64 encodeData:self];
    NSString* base64String = [[NSString alloc]initWithData:data encoding:encoding];
    return base64String;
    
}

// 按照UTF8字符集执行base64解码
- (NSString*)base64DecodingForUTF8{
    return [self base64DecodingForEncoding:NSUTF8StringEncoding];
}

// 按照指定字符集执行base64解码
- (NSString*)base64DecodingForEncoding:(NSStringEncoding)encoding{
    NSData *data = [GTMBase64 decodeData:self];
    NSString*base64String = [[NSString alloc]initWithData:data encoding:encoding] ;
    return base64String;
}

/**  --# base64编码处理 ↑ #--  **/


#pragma mark - String Conversion
- (NSString *)hexadecimalString
{
    /* Returns hexadecimal string of NSData. Empty string if data is empty.   */
    
    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
    
    if (!dataBuffer)
    {
        return [NSString string];
    }
    
    NSUInteger          dataLength  = [self length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i)
    {
        [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }
    
    return [NSString stringWithString:hexString];
}

@end
